package com.hopkinscsc.windows;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.swing.JPanel;



/*
 * This class is the backbone of the entire framework. The user never works with it but everything that happens uses it.
 */
public class Engine extends JPanel implements Runnable {
	
	private int FPS = 1000/30;
	private Collection<Element> elements = new ArrayList<Element>();
	/*
	 *  
	 */
	public Engine(){
		new Thread(this).start();
	}
	/**
	 * This adds a new element to the ArrayList so that it can be drawn onto the screen
	 * @param element the element to add
	 */
	public void addElement(Element element){
		System.out.println("adding element");
		elements.add(element);
	}
	
	@Override
	public void run() {
		long tm = System.currentTimeMillis();

        while(true){
        	update();
        	repaint();
            try {
                tm += FPS;
                Thread.sleep(Math.max(40, tm - System.currentTimeMillis()));
            }catch(InterruptedException e){
            	System.out.println(e);
            }
        }
	}
	
	public void paint(Graphics g){
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, getWidth(), getHeight());
		
		Iterator iterator = elements.iterator();
		Element thisElement;
		
		while(iterator.hasNext()){
			thisElement = ((Element) iterator.next());
			thisElement.draw(g);
		}
	}

	public void update(){
		Element thisElement;
		Iterator iterator = elements.iterator();
		
		while(iterator.hasNext()){
			thisElement = ((Element) iterator.next());
			thisElement.update();
		}
	}
}
